<?  include_once('../../../config.php');
    include_once('../../../ldapConnect.php');

/**
 * Controlador para la subida de avatares.
 *
 * @package html
 *
 */
class EditAvatar{

	/**
	 * Opciones recogidas para hacerlas visibles fuera de la clase
	 * @var array indexado por nombres de opción
	 */
	public $opt;

	/**
	 * Datos a mostrar en la vista, tales como los desplegables
	 * @var array indexado por nombre de la lista
	 */
	public $datos;

        /**
         * Atributos a utilizar durante el tiempo de vida del objeto
         */

        public $Usuario;

        public $error;

        // Constante que se van a utilizar:
        public $upload_dir; 		// The directory for the images to be saved in
        public $upload_path;		// The path to where the image will be saved
        public $large_image_prefix; 	// The prefix name to large image
        public $thumb_image_prefix;	// The prefix name to the thumb image
        public $large_image_name;       // New name of the large image (append the timestamp to the filename)
        public $thumb_image_name;       // New name of the thumbnail image (append the timestamp to the filename)
        public $max_file; 		// Maximum file size in MB
        public $max_width;		// Max width allowed for the large image
        public $thumb_width;		// Width of thumbnail image
        public $thumb_height;		// Height of thumbnail image
        public $allowed_image_types;    // Only one of these image types should be allowed for upload
        public $allowed_image_ext;      
        public $image_ext;

        public $large_image_location;
        public $thumb_image_location;

        public $large_photo_exists;
        public $thumb_photo_exists;

        public $imagen_guardada;
        
        /**
	 * Constructor de la clase
	 *
	 */
	public function __construct($opciones_get, $opciones, $opciones_archivo){
            try{
                //FB::info($opciones_get,'$_GET');FB::info($opciones,'$_POST');FB::info($opciones_archivo,'$_FILE');
                session_start();
                $this->obtener_Opciones($opciones_get, $opciones, $opciones_archivo);
                
                //only assign a new timestamp if the session variable is empty
                if (!isset($_SESSION['random_key']) || strlen($_SESSION['random_key'])==0){
                    $_SESSION['random_key'] = time();
                    $_SESSION['user_file_ext']= "";
                }
                
                $this->inicializar_Datos();
                

                if ($this->opt["upload"]) {
                    $this->upload();
                }
                if ($this->opt["upload_thumbnail"] && strlen($this->large_photo_exists)>0) {
                    $this->upload_thumbnail();
                }
                if ($this->opt['a']=="delete" && $this->opt['t']){
                    $this->delete();
                }


            }catch(Exception $e){
                $this->error = $e->getMessage();
            }
	}

        private function inicializar_Datos(){
            $this->upload_dir = "avatares"; 				// The directory for the images to be saved in
            $this->upload_path = $this->upload_dir."/";				// The path to where the image will be saved
            $this->large_image_prefix = "resize_"; 			// The prefix name to large image
            $this->thumb_image_prefix = "";			// The prefix name to the thumb image
            $this->large_image_name = $this->large_image_prefix.$this->Usuario->get_Id();     // New name of the large image (append the timestamp to the filename)
            $this->thumb_image_name = $this->thumb_image_prefix.$this->Usuario->get_Id();     // New name of the thumbnail image (append the timestamp to the filename)
            $this->max_file = "3"; 							// Maximum file size in MB
            $this->max_width = "500";							// Max width allowed for the large image
            $this->thumb_width = "100";						// Width of thumbnail image
            $this->thumb_height = "100";						// Height of thumbnail image
            // Only one of these image types should be allowed for upload
            $this->allowed_image_types = array('image/pjpeg'=>"jpg",'image/jpeg'=>"jpg",'image/jpg'=>"jpg",'image/png'=>"png",'image/x-png'=>"png",'image/gif'=>"gif");
            $this->allowed_image_ext = array_unique($this->allowed_image_types); // do not change this
            $this->image_ext = "";	// initialise variable, do not change this.
            foreach ($this->allowed_image_ext as $mime_type => $ext) {
                $this->image_ext.= strtoupper($ext)." ";
            }

            //Image Locations
            $this->large_image_location = $this->upload_path.$this->large_image_name.$_SESSION['user_file_ext'];
            $this->thumb_image_location = $this->upload_path.$this->thumb_image_name.$_SESSION['user_file_ext'];

            $this->actualizar_Imagenes();
        }

        private function actualizar_Imagenes(){

            //Check to see if any images with the same name already exist
            if (file_exists($this->large_image_location)){
                if(file_exists($this->thumb_image_location)){
                    $this->thumb_photo_exists = "<img src=\"".$this->upload_path.$this->thumb_image_name."\" alt=\"Thumbnail Image\"/>";
                }else{
                    $this->thumb_photo_exists = "";
                }
                $this->large_photo_exists = "<img src=\"".$this->upload_path.$this->large_image_name."\" alt=\"Large Image\"/>";
            } else {
                $this->large_photo_exists = "";
                $this->thumb_photo_exists = "";
            }
        }

	private function obtener_Opciones($opciones_get, $opciones, $opciones_archivo){
            @($opciones_archivo['image'])?$this->opt['image']=$opciones_archivo['image']:null;
            @($opciones['upload'])?$this->opt['upload']=$opciones['upload']:null;
            @($opciones['upload_thumbnail'])?$this->opt['upload_thumbnail']=$opciones['upload_thumbnail']:null;

            @($opciones['x1'])?$this->opt['x1']=$opciones['x1']:null;
            @($opciones['x2'])?$this->opt['x2']=$opciones['x2']:null;
            @($opciones['y1'])?$this->opt['y1']=$opciones['y1']:null;
            @($opciones['y2'])?$this->opt['y2']=$opciones['y2']:null;
            @($opciones['w'])?$this->opt['w']=$opciones['w']:null;
            @($opciones['h'])?$this->opt['h']=$opciones['h']:null;

            @($opciones_get['a'])?$this->opt['a']=$opciones_get['a']:null;
            @($opciones_get['t'])?$this->opt['t']=$opciones_get['t']:null;

            if($opciones_get['id_usuario']){
                $this->opt['id_usuario'] = $opciones_get['id_usuario'];
                //FB::info($opciones_get['id_usuario'],'ha pillado el id usuario GET');
            }
            else{
                $this->opt['id_usuario'] = $opciones['id_usuario'];
                //FB::info($opciones['id_usuario'],'ha pillado el id usuario POST');
            }
            
            $this->Usuario = new Usuario($this->opt['id_usuario']);
	}

        private function upload(){
            //Get the file information
            $userfile_name = $this->opt['image']['name'];
            $userfile_tmp = $this->opt['image']['tmp_name'];
            $userfile_size = $this->opt['image']['size'];
            $userfile_type = $this->opt['image']['type'];
            $filename = basename($this->opt['image']['name']);
            $file_ext = strtolower(substr($filename, strrpos($filename, '.') + 1));

            //Only process if the file is a JPG, PNG or GIF and below the allowed limit
            if((!empty($this->opt["image"])) && ($this->opt['image']['error'] == 0)) {

                foreach ($this->allowed_image_types as $mime_type => $ext) {
                    //loop through the specified image types and if they match the extension then break out
                    //everything is ok so go and check file size
                    if($file_ext==$ext && $userfile_type==$mime_type){
                        $this->error = "";
                        break;
                    }else{
                        $this->error = "Error. Formatos permitidos: <strong>".$image_ext;
                    }
                }
                //check if the file size is above the allowed limit
                if ($userfile_size > ($this->max_file*1048576)) {
                    $this->error.= "Error. Tama&ntilde;o m&aacute;ximo ".$this->max_file."MB";
                }

            }else{
                $this->error= "Selecciona una imagen";
            }
            //Everything is ok, so we can upload the image.
            if (strlen($this->error)==0){

                if (isset($this->opt['image']['name'])){
                    //this file could now has an unknown file extension (we hope it's one of the ones set above!)

                    if($_SESSION['user_file_ext']){
                        $this->large_image_location = $this->large_image_location;
                        $this->thumb_image_location = $this->thumb_image_location;
                    }else{
                        $this->large_image_location = $this->large_image_location.".".$file_ext;
                        $this->thumb_image_location = $this->thumb_image_location.".".$file_ext;
                    }
                    //put the file ext in the session so we know what file to look for once its uploaded
                    $_SESSION['user_file_ext']=".".$file_ext;

                    move_uploaded_file($userfile_tmp, $this->large_image_location);
                    chmod($this->large_image_location, 0777);

                    $width = Imagenes::getWidth($this->large_image_location);
                    $height = Imagenes::getHeight($this->large_image_location);
                    //Scale the image if it is greater than the width set above
                    if ($width > $this->max_width){
                        $scale = $this->max_width/$width;
                        $uploaded = Imagenes::resizeImage($this->large_image_location,$width,$height,$scale);
                    }else{
                        $scale = 1;
                        $uploaded = Imagenes::resizeImage($this->large_image_location,$width,$height,$scale);
                    }                    
                }

                $this->actualizar_Imagenes();
                $this->ok = "Imagen subida";
                //Refresh the page to show the new uploaded image
                //header("location:".$_SERVER["PHP_SELF"]);
                //exit();
            }
        }

        private function upload_thumbnail(){
            //Delete the thumbnail file so the user can create a new one
            if (file_exists($this->thumb_image_location)) {
                    unlink($this->thumb_image_location);
            }
            //Get the new coordinates to crop the image.
            $x1 = $this->opt["x1"];
            $y1 = $this->opt["y1"];
            $x2 = $this->opt["x2"];
            $y2 = $this->opt["y2"];
            $w = $this->opt["w"];
            $h = $this->opt["h"];
            //Scale the image to the thumb_width set above
            $scale = $this->thumb_width/$w;
            $cropped = Imagenes::resizeThumbnailImage($this->thumb_image_location, $this->large_image_location,$w,$h,$x1,$y1,$scale);
            
            //Delete the thumbnail file so the user can create a new one
            if(file_exists($this->large_image_location))
                unlink($this->large_image_location);

            $this->actualizar_Imagenes();
            $this->ok = "Imagen de perfil guardada";

            $this->Usuario->set_Imagen_Subida();
            $this->imagen_guardada = 1;
            //Reload the page again to view the thumbnail
            //header("location:".$_SERVER["PHP_SELF"]);
            //exit();
        }

        private function delete(){
            //get the file locations
            $this->large_image_location = $this->upload_path.$this->large_image_prefix.$this->opt['t'];
            $this->thumb_image_location = $this->upload_path.$this->thumb_image_prefix.$this->opt['t'];
            
            if (file_exists($this->large_image_location)) {
                unlink($this->large_image_location);
            }
            if (file_exists($this->thumb_image_location)) {
                unlink($this->thumb_image_location);
            }
            //header("location:".$_SERVER["PHP_SELF"]);
            //exit();
        }

}

?>